package com.call.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.ContactsContract.PhoneLookup;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.call.R;
import com.call.data.MissCallData;
import com.call.data.MissSMSData;
import com.call.service.IMissCallAndPhoneNumberService;
import com.call.service.ISMSService;
import com.call.service.MissCallAndPhoneNumberService;
import com.call.service.SMSService;
import com.call.widget.WidgetProvider;

public class MainActivity extends ListActivity 
{
	private final String TAG = "DEBUG";
	
	private ListView m_view;
	private int m_nowDataCount;
	private ArrayList<HashMap<String, Object>> m_data;

	private MyAdapter mListAdapter;
    private IMissCallAndPhoneNumberService callBindedService = null;
    private ISMSService msmBindedService = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        m_nowDataCount = 0;
        m_data = new ArrayList<HashMap<String, Object>>();
    	Toast.makeText(this.getApplicationContext(), "onCreate", Toast.LENGTH_SHORT).show();

        ConnectService();
        UpdateWidget();

        m_view = (ListView)getListView();
        mListAdapter = new MyAdapter(this);
		m_view.setAdapter(mListAdapter);
    }   
     
	@Override
	protected void onResume() 
	{
		Log.v(TAG, "onResume");
		super.onResume();
		ConnectService();
	}
	
	@Override
	protected void onStop() {
    	try
    	{
    		this.unbindService(call_conn);
    		this.unbindService(sms_conn);
    	}catch (Exception e) {
			// TODO: handle exception
		}
		super.onStop();
	}

	
    @Override
    public void onDestroy()
    {
    	try
    	{
    		this.unbindService(call_conn);
    		this.unbindService(sms_conn);
    	}catch (Exception e) {
			// TODO: handle exception
		}
    	super.onDestroy();
    }
    
    
    private void ConnectService() 
    {
    	Log.v(TAG, "ConnectService");
		Intent i = new Intent(this, MissCallAndPhoneNumberService.class); 
    	if (!isServiceRunning())
    	{
    		this.startService(i);
    		this.bindService(i, call_conn, Context.BIND_AUTO_CREATE);
    		Toast.makeText(this.getApplicationContext(), "Call Service Start", Toast.LENGTH_SHORT).show();
    		
    	}
    	else
    	{
    		this.bindService(i, call_conn, Context.BIND_AUTO_CREATE);
    	}
    	
    	Intent i2 = new Intent(this, SMSService.class); 
    	if (!SMSService.isInstanceCreated())
    	{
    		//Log.v("SMSService")
    		this.startService(i2);
    		this.bindService(i2, sms_conn, Context.BIND_AUTO_CREATE);
    		Toast.makeText(this.getApplicationContext(), "SMS Service Start", Toast.LENGTH_SHORT).show();
    		
    	}
    	else
    	{
    		this.bindService(i2, sms_conn, Context.BIND_AUTO_CREATE);
    	}
    	
    	
    	UpdateWidget();
    }
    
    private void DeleteService() 
    {
    	
    	Log.v(TAG, "ConnectService");
    	try
    	{
    		this.unbindService(call_conn);
    		this.unbindService(sms_conn);
    	}
    	catch (Exception e) {
			// TODO: handle exception
		}
    	Intent i = new Intent(this, MissCallAndPhoneNumberService.class); 
    	Intent i2 = new Intent(this, SMSService.class); 
    	
    	this.stopService(i);
    	this.stopService(i2);
    	
    	UpdateWidget();
    	Toast.makeText(this.getApplicationContext(), "Service stopped", Toast.LENGTH_SHORT).show();
    }
    private boolean isServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) 
        {
        	//Log.v(Constants.Tag, service.service.getClassName());
//            if ("com.call.service.MissCallAndPhoneNumberService".equals(service.service.getClassName()))
            if ("com.call.service.MissCallAndPhoneNumberService".equals(service.service.getClassName())
            		&&  "com.call.service.SMSService".equals(service.service.getClassName())
            	)
            {
                return true;
            }
        }
        return false;
    }
    private void GetMissCallData()
    {
    	Log.v(TAG, "GetMissCallData");
    	Cursor c = callBindedService.GetMissCallInfo();//m_nowDataCount, m_nowDataCount + 10);
    	int numberColumnIndex = c.getColumnIndex(MissCallData.TableColumns.CallNumber);
    	int timeIndex = c.getColumnIndex(MissCallData.TableColumns.CallTime);
    	int idIndex = c.getColumnIndex(MissCallData.TableColumns._ID);
    	if(c.moveToFirst())
    	{
        	Log.v(TAG, "c.moveToFirst()");
        	m_data.clear();
	    	do{
	    		HashMap<String, Object> item = new HashMap<String, Object>();
	    		long time = c.getLong(timeIndex);
	    		String number = c.getString(numberColumnIndex);
	    		
	    		int _id = c.getInt(idIndex);
	    		String[] columns = new String[]{PhoneLookup.DISPLAY_NAME};
	    		ContentResolver conR = getContentResolver();
	    		Uri phoneBookUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
	    		Cursor result = conR.query(phoneBookUri, columns, null, null, null);
	    		String userName = number;
	    		if(result.moveToFirst())
	    		{
	    			int nameIndex = result.getColumnIndex(PhoneLookup.DISPLAY_NAME);
	    			userName = result.getString(nameIndex);
	    		}
	    		item.put("id", _id);
	    		item.put("name", userName);
	    		item.put("num", number);

	    		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");     
	    		Date curDate = new Date(time); 
	    		String str = formatter.format(curDate); 
	    		item.put("time",  str);
	    		item.put("img", R.drawable.attention);
	    		m_data.add(item);
	    		m_nowDataCount += 1;
	    	}while(c.moveToNext());
    	}
    	c.close();
    }
    
    private boolean deleteData(int id , int nPos)
    {
    	if(this.callBindedService != null)
    	{
    		//this.msmBindedService.DeleteSMSReceiverInfo(id);
    		this.callBindedService.DeleteMissCallInfo(id);
    		m_data.remove(nPos);
    	}
    	return true;
    }
    
    private void UpdateWidget()
    {
    	Log.v(TAG, "UpdateWidget" + String.valueOf(WidgetProvider.startService) );
    	
        Intent i = new Intent(this, WidgetProvider.class); 
        i.setAction(WidgetProvider.UPDATE_ACTION); 
        sendBroadcast(i); 
    }
    
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		String strRecall = (String)m_data.get(position).get("num");
		Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel://" + strRecall));
		MainActivity.this.startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, 1, 1, R.string.menu_del);
		if (isServiceRunning())
			menu.add(0, 2, 2, R.string.menu_close_service);
		else
			menu.add(0, 2, 2, R.string.menu_start_service);
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) 
	{
		menu.clear();
		menu.add(0, 1, 1, R.string.menu_del);
		if (isServiceRunning())
			menu.add(0, 2, 2, R.string.menu_close_service);
		else
			menu.add(0, 2, 2, R.string.menu_start_service);
		return super.onPrepareOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		switch(item.getItemId())
		{
		case 1:
			while(!m_data.isEmpty())
			{
				deleteData((Integer)m_data.get(0).get("id"), 0);
			}
			mListAdapter.notifyDataSetChanged();
			break;
		case 2:
			if (isServiceRunning())
				DeleteService();
			else
				ConnectService();
			
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private ServiceConnection call_conn = new ServiceConnection() {
	    public void onServiceConnected(ComponentName name, IBinder service) {
	    	callBindedService = (IMissCallAndPhoneNumberService)service;
	    	Log.v(TAG, "new call_conn");
	    	GetMissCallData();
	    	
	    	mListAdapter.notifyDataSetChanged();
	    	mListAdapter.notifyDataSetInvalidated();	
	    }
	    
	    public void onServiceDisconnected(ComponentName arg0) {
	    	callBindedService = null;
	    	//Log.i(Constants.Tag,"disconnected service");
	    }
	    
	    
	};
	
	private ServiceConnection sms_conn = new ServiceConnection() {
	    public void onServiceConnected(ComponentName name, IBinder service) {
	    	msmBindedService = (ISMSService)service;
	    	Log.v(TAG, "new sms_conn");
	    	//GetMissSMSData();
	    	
	    	mListAdapter.notifyDataSetChanged();
	    	mListAdapter.notifyDataSetInvalidated();	
	    }
	    
	    public void onServiceDisconnected(ComponentName arg0) {
	    	msmBindedService = null;
	    	//Log.i(Constants.Tag,"disconnected service");
	    }
	    
	    
	};
	
	/* inner class */
	/*
	 * Adapter for ListView
	 */
	public class MyAdapter extends BaseAdapter
    {    	
    	public MyAdapter(Context context)
    	{
    		this.m_inflater = LayoutInflater.from(context);
    	}

		public int getCount() {
			return m_data.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

	
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			if(convertView == null)
			{
				holder = new ViewHolder();
				convertView = m_inflater.inflate(R.layout.call_list, null);
				holder.m_imgContact = (ImageView)convertView.findViewById(R.id.imgContact);
				holder.m_txtName = (TextView)convertView.findViewById(R.id.txtName);
				holder.m_txtNum = (TextView)convertView.findViewById(R.id.txtNum);
				holder.m_txtTime = (TextView)convertView.findViewById(R.id.txtTime);
				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder)convertView.getTag();
			}

			String nameContact = (String)m_data.get(position).get("name");
			String numContact = (String)m_data.get(position).get("num");

			holder.m_imgContact.setBackgroundResource((Integer)m_data.get(position).get("img"));
			holder.m_txtName.setText(nameContact);
			if (nameContact.equals(numContact))
				holder.m_txtNum.setText("");
			else
				holder.m_txtNum.setText(numContact);
			holder.m_txtTime.setText((String)m_data.get(position).get("time"));
			return convertView;
		}
    	
		public final class ViewHolder
		{
			public TextView m_txtName;
			public TextView m_txtNum;
			public TextView m_txtTime;
			public ImageView m_imgContact;
		}
		
		private LayoutInflater m_inflater;
    	ViewHolder holder = null;
    }
}